package xyz.itpath.tools;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaom
 * @date 2021/9/11 - 10:31
 * <br/>
 */
public class CodeManager {
    /**
     * 编码缓存map
     */
    private static final Map<String, String> CODE_MAP = new HashMap<>();

    /**
     * 设置编码缓存
     *
     * @param idOfCode 编码的id
     * @param code     存入的编码
     * @param delay    过期的时间 ms
     */
    public void putCode(String idOfCode, String code, Long delay, TimeUnit timeUnit) {
        synchronized (CODE_MAP) {
            CODE_MAP.put(idOfCode, code);
            ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1);
            executor.schedule( ()-> removeCode(idOfCode) , delay, timeUnit);
        }
    }

    /**
     * 获取编码
     *
     * @param idOfCode
     * @return
     */
    public String getCode(String idOfCode) {
        synchronized (CODE_MAP) {
            return CODE_MAP.get(idOfCode);
        }
    }

    public synchronized boolean containCodeById(String idOfCode) {
        return CODE_MAP.containsKey(idOfCode);
    }

    /**
     * 比对编码,如果比对成功，则移除该编码
     *
     * @return
     */
    public synchronized boolean compareCode(String idOfCode, String code) {
        if (!CODE_MAP.containsKey(idOfCode)) {
            return false;
        }
        if (CODE_MAP.get(idOfCode).equals(code)) {
            removeCode(idOfCode);
            return true;
        }
        return false;
    }

    /**
     * 移除编码
     */
    public void removeCode(String idOfCode) {
        CODE_MAP.remove(idOfCode);
    }
}
